import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ListService, PagedResultDto } from '@abp/ng.core';
import { OrdersService } from './orders.service';
import { OrderDto, CreateUpdateOrderDto } from './models';
import { Subscription } from 'rxjs';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-orders',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule],
  templateUrl: './orders.component.html',
  styleUrls: ['./orders.component.scss'],
  providers: [ListService]
})
export class OrdersComponent implements OnInit, OnDestroy {
  orders = { items: [], totalCount: 0 } as PagedResultDto<OrderDto>;
  createOrderForm: FormGroup;
  isModalOpen = false;
  isEditMode = false;
  selectedOrderId: string;
  isSaving = false;
  Math = Math;

  pageSizeOptions = [10, 20, 30, 50];
  currentPageSize = 10;
  maxPageCount = 1;
  visiblePageNumbers: number[] = [];
  inputPageNumber: number = 1;

  private subscription: Subscription = new Subscription();

  orderNumberKeyword = '';
  senderKeyword = '';
  receiverKeyword = '';
  isSearchMode = false;
  isLoading = false;

  constructor(
    public readonly list: ListService,
    private ordersService: OrdersService,
    private fb: FormBuilder
  ) {
    this.createOrderForm = this.fb.group({
      shipper: ['', Validators.required],
      shipperPhone: ['', Validators.required],
      shipperAddress: ['', Validators.required],
      consignee: ['', Validators.required],
      consigneePhone: ['', Validators.required],
      consigneeAddress: ['', Validators.required],
      goods: ['', Validators.required],
      pieceCount: [1, [Validators.required, Validators.min(1)]],
      declaration: ['自提', Validators.required],
      lengthm: [1, [Validators.required, Validators.min(0)]],
      widthm: [1, [Validators.required, Validators.min(0)]],
      heightm: [1, [Validators.required, Validators.min(0)]],
      weightk: [1, [Validators.required, Validators.min(0)]],
      freightAmount: [0, [Validators.required, Validators.min(0)]],
      returnRequired: ['否', Validators.required],
      status: [true],
      customerNo: [null, Validators.required],
      remarks: [''],
      orderNo: [null],
    });
  }

  ngOnInit() {
    this.list.page = 1;
    this.loadData();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  loadData() {
    if (this.list.page <= 0) {
      this.list.page = 1;
    }
    this.isLoading = true;
    const streamCreator = (query) => {
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      return this.ordersService.getList(params);
    };
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(finalize(() => { this.isLoading = false; }))
        .subscribe(
          (response: PagedResultDto<OrderDto>) => {
            let items = response.items;
            if (this.isSearchMode) {
              items = items.filter(item => {
                const orderNumberMatch = !this.orderNumberKeyword.trim() || (item.OrderNo && item.OrderNo.toString().includes(this.orderNumberKeyword.trim()));
                const senderMatch = !this.senderKeyword.trim() || (item.Shipper && item.Shipper.includes(this.senderKeyword.trim()));
                const receiverMatch = !this.receiverKeyword.trim() || (item.Consignee && item.Consignee.includes(this.receiverKeyword.trim()));
                return orderNumberMatch && senderMatch && receiverMatch;
              });
            }
            this.orders = { ...response, items };
            if (response.totalCount > 0) {
              this.maxPageCount = Math.ceil(response.totalCount / this.currentPageSize);
              if (this.list.page > this.maxPageCount) {
                this.list.page = this.maxPageCount;
                if (response.items.length === 0) {
                  this.loadDataWithoutCheck();
                }
              }
            } else {
              this.maxPageCount = 1;
              this.list.page = 1;
            }
            this.updateVisiblePageNumbers();
          },
          error => {
            // 错误处理
          }
        )
    );
  }

  loadDataWithoutCheck() {
    this.isLoading = true;
    const streamCreator = (query) => {
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      return this.ordersService.getList(params);
    };
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(finalize(() => { this.isLoading = false; }))
        .subscribe(
          (response: PagedResultDto<OrderDto>) => {
            this.orders = response;
            this.updateVisiblePageNumbers();
          },
          error => {
            // 错误处理
          }
        )
    );
  }

  updateVisiblePageNumbers() {
    const currentPage = this.list.page || 1;
    const pageNumbers = [];
    if (this.maxPageCount <= 5) {
      for (let i = 1; i <= this.maxPageCount; i++) {
        pageNumbers.push(i);
      }
    } else {
      if (currentPage > 3) {
        pageNumbers.push(1, -1);
      }
      let start = Math.max(1, currentPage - 2);
      let end = Math.min(this.maxPageCount, currentPage + 2);
      for (let i = start; i <= end; i++) {
        pageNumbers.push(i);
      }
      if (end < this.maxPageCount) {
        pageNumbers.push(-1, this.maxPageCount);
      }
    }
    this.visiblePageNumbers = pageNumbers;
  }

  onPageSizeChange(pageSize: number) {
    this.currentPageSize = pageSize;
    this.list.page = 1;
    this.loadData();
  }

  goToPage(page: number) {
    if (page < 1 || page > this.maxPageCount) return;
    this.list.page = page;
    this.loadData();
  }

  onPageInputChange(event: Event) {
    const value = (event.target as HTMLInputElement).value;
    const page = Number(value);
    if (!isNaN(page)) {
      this.inputPageNumber = page;
    }
  }

  onPageInputKeyUp(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }

  search() {
    this.isSearchMode = true;
    this.list.page = 1;
    this.loadData();
  }

  resetSearch() {
    this.orderNumberKeyword = '';
    this.senderKeyword = '';
    this.receiverKeyword = '';
    this.isSearchMode = false;
    this.list.page = 1;
    this.loadData();
  }

  openCreateModal() {
    this.isModalOpen = true;
    this.isEditMode = false;
    const now = new Date();
    const pad = (n: number, len = 2) => n.toString().padStart(len, '0');
    const orderNo =
      now.getFullYear().toString() +
      pad(now.getMonth() + 1) +
      pad(now.getDate()) +
      pad(now.getHours()) +
      pad(now.getMinutes()) +
      pad(now.getSeconds()) +
      pad(now.getMilliseconds(), 3);
    this.createOrderForm.reset({
      shipper: '',
      shipperPhone: '',
      shipperAddress: '',
      consignee: '',
      consigneePhone: '',
      consigneeAddress: '',
      goods: '',
      pieceCount: 1,
      declaration: '自提',
      lengthm: 1,
      widthm: 1,
      heightm: 1,
      weightk: 1,
      freightAmount: 0,
      returnRequired: '否',
      status: true,
      customerNo: null,
      remarks: '',
      orderNo: orderNo,
    });
  }

  openEditModal(orderId: string) {
    this.isModalOpen = true;
    this.isEditMode = true;
    this.selectedOrderId = orderId;
    this.ordersService.get(orderId).subscribe(
      (orderData) => {
        this.createOrderForm.patchValue(orderData);
        if (orderData.OrderNo) {
          this.createOrderForm.addControl('OrderNo', this.fb.control(orderData.OrderNo));
        }
      },
      (error) => {
        this.closeModal();
      }
    );
  }
  closeModal() {
    this.isModalOpen = false;
    this.createOrderForm.reset();
    this.createOrderForm.patchValue({
      orderNo: '',
      shipper: '',
      shipperPhone: '',
      shipperAddress: '',
      consignee: '',
      consigneePhone: '',
      consigneeAddress: '',
      goodsType: '',
      weight: 0,
      volume: 0,
      amount: 0,
      unit: '',
      deliveryType: '',
      paymentType: '',
      remarks: '',
      status: ''
    }, {emitEvent: false});
  }

  save() {
    if (this.createOrderForm.invalid) {
      Object.keys(this.createOrderForm.controls).forEach(key => {
        const control = this.createOrderForm.get(key);
        control.markAsDirty();
        control.markAsTouched();
      });
      return;
    }
    const orderData = this.createOrderForm.value as CreateUpdateOrderDto;
    this.isSaving = true;
    if (this.isEditMode) {
      this.ordersService.update(this.selectedOrderId, orderData).subscribe(
        () => {
          this.isModalOpen = false;
          this.createOrderForm.reset();
          this.loadData();
          this.isSaving = false;
        },
        (error) => {
          this.isSaving = false;
        }
      );
    } else {
      this.ordersService.create(orderData).subscribe(
        () => {
          this.isModalOpen = false;
          this.createOrderForm.reset();
          this.loadData();
          this.isSaving = false;
        },
        (error) => {
          this.isSaving = false;
        }
      );
    }
  }

  deleteOrder(orderId: string) {
    if (!window.confirm('确定要删除该订单吗？')) {
      return;
    }
    this.ordersService.delete(orderId).subscribe(
      () => {
        if (this.orders.items.length === 1 && this.list.page > 1) {
          this.list.page--;
        }
        this.loadData();
      },
      (error) => {
      }
    );
  }
}